//
//  CheckNetwork.m
//  CheckNetworkTest
//
//  Created by shudan on 12/20/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//
#import <sys/socket.h>
#import <netinet/in.h>
#import <netinet6/in6.h>
#import <arpa/inet.h>
#import <ifaddrs.h>
#import <netdb.h>

#import <CoreFoundation/CoreFoundation.h>
#import "CheckNetwork.h"
//#import "macTool.h"

//#import "UIDevice-IOKit.h"

static CheckNetwork *checkNetwork = nil;

static int	nNetType;
static BOOL bShowAlert;
@implementation CheckNetwork

@synthesize localWiFiRef;
@synthesize reachabilityRef;

+ (CheckNetwork*)shareCheckNetwork
{
	@synchronized(self)
	{
		if (checkNetwork == nil) {
			checkNetwork = [[CheckNetwork alloc] init];
		}
    bShowAlert = YES;
		return checkNetwork;
	}
	
}

-(id)init
{
	if (isStartCheckNet == 1) {//启动网络检测
		[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(reachabilityChanged:) name: kReachabilityChangedNotification object: nil];
		//[self checkNetworkTypeToURL];
	}
	[self getUUID];
	return [super init];
}

-(int)getNetType
{
	printf("\n 网络类型 %d",nNetType);
	return nNetType;
}

-(int)checkNetworkTypeToURL
{
	[NSThread detachNewThreadSelector:@selector(startTheBackgroundJob) toTarget:self withObject:nil];
	return 0;
}

- (void)startTheBackgroundJob 
{
	
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    [self performSelectorOnMainThread:@selector(currentReachabilityStatus) withObject:nil waitUntilDone:NO];
    [pool release];
	
}

-(void)startThread
{
	//int type = noUsableNetwork;
	
	/*NSString *hostName = @"www.apple.com"; 
	SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(NULL, [hostName UTF8String]);
	
	if(reachability!= NULL)
	{
		reachabilityRef = reachability;
		localWiFiRef = NO;
		
	}*/
	
	struct sockaddr_in zeroAddress;
	bzero(&zeroAddress, sizeof(zeroAddress));
	zeroAddress.sin_len = sizeof(zeroAddress);
	zeroAddress.sin_family = AF_INET;
	SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr*)&zeroAddress);

	if(reachability!= NULL)
	{
		reachabilityRef = reachability;
		localWiFiRef = NO;
	}
	
	
	[self checkNetworkTypeToURL];
}

//Called by Reachability whenever status changes.
- (void) reachabilityChanged: (NSNotification* )note
{
	[self checkNetworkTypeToURL];
}

- (PANetworkStatus) currentReachabilityStatus
{
	NSAssert(reachabilityRef != NULL, @"currentNetworkStatus called with NULL reachabilityRef");
	PANetworkStatus retVal = noUsableNetwork;
	SCNetworkReachabilityFlags flags;
	if (SCNetworkReachabilityGetFlags(reachabilityRef, &flags))
	{
		if(localWiFiRef)
		{
			retVal = [self localWiFiStatusForFlags: flags];
		}
		else
		{
			retVal = [self networkStatusForFlags: flags];
		}
	}
	nNetType = retVal;
	printf("\n 网络状态 %d",nNetType);
	
	if (bShowAlert) {//显示
		NSString *s;
		if (nNetType == noUsableNetwork) {
			//[[QuoteModel shareQuoteModel]sendNoNetMessage];
			s = [NSString stringWithFormat:@"当前网络为：无网络可用\n您可以在设置中，设置是否显示"];
      
      UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"网络状态提示"
                                                          message:s
                                                         delegate:self
                                                cancelButtonTitle:@"不再显示"
                                                otherButtonTitles:nil];
      [alertView addButtonWithTitle:@"确定"];
      [alertView show];
      [alertView release];
      
		}else if (nNetType == usableNetworkViaWiFi) {
			s = [NSString stringWithFormat:@"当前网络为：WIFI\n您可以在设置中，设置是否显示"];
		}else if (nNetType == usableNetworkViaWWAN) {
			s = [NSString stringWithFormat:@"当前网络为：3G(GPRS)\n您可以在设置中，设置是否显示"];
		}

	}
	return retVal;
}

#pragma mark Network Flag Handling

- (PANetworkStatus) localWiFiStatusForFlags: (SCNetworkReachabilityFlags) flags
{	
	BOOL retVal = noUsableNetwork;
	if((flags & kSCNetworkReachabilityFlagsReachable) && (flags & kSCNetworkReachabilityFlagsIsDirect))
	{
		retVal = usableNetworkViaWiFi;	
	}
	return retVal;
}

- (PANetworkStatus) networkStatusForFlags: (SCNetworkReachabilityFlags) flags
{
	if ((flags & kSCNetworkReachabilityFlagsReachable) == 0)
	{
		// if target host is not reachable
		return noUsableNetwork;
	}
	
	BOOL retVal = noUsableNetwork;
	
	if ((flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0)
	{
		// if target host is reachable and no connection is required
		//  then we'll assume (for now) that your on Wi-Fi
		retVal = usableNetworkViaWiFi;
	}
	
	
	if ((((flags & kSCNetworkReachabilityFlagsConnectionOnDemand ) != 0) ||
		 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0))
	{
		// ... and the connection is on-demand (or on-traffic) if the
		//     calling application is using the CFSocketStream or higher APIs
		
		if ((flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0)
		{
			// ... and no [user] intervention is needed
			retVal = usableNetworkViaWiFi;
		}
	}
	
	if ((flags & kSCNetworkReachabilityFlagsIsWWAN) == kSCNetworkReachabilityFlagsIsWWAN)
	{
		// ... but WWAN connections are OK if the calling application
		//     is using the CFNetwork (CFSocketStream?) APIs.
		retVal = usableNetworkViaWWAN;
	}
	return retVal;
}

static void ReachabilityCallback(SCNetworkReachabilityRef target, SCNetworkReachabilityFlags flags, void* info)
{
#pragma unused (target, flags)
	NSCAssert(info != NULL, @"info was NULL in ReachabilityCallback");
	NSCAssert([(NSObject*) info isKindOfClass: [CheckNetwork class]], @"info was wrong class in ReachabilityCallback");
	
	//We're on the main RunLoop, so an NSAutoreleasePool is not necessary, but is added defensively
	// in case someon uses the Reachablity object in a different thread.
	NSAutoreleasePool* myPool = [[NSAutoreleasePool alloc] init];
	
	CheckNetwork *noteObject = (CheckNetwork*)info;
	// Post a notification to notify the client that the network reachability changed.
	[[NSNotificationCenter defaultCenter] postNotificationName: kReachabilityChangedNotification object:noteObject];
	
	[myPool release];
}

- (BOOL) startNotifier
{
	BOOL retVal = NO;
	if (isStartCheckNet == 1) {
		[self startThread];
		SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
		if(SCNetworkReachabilitySetCallback(reachabilityRef, ReachabilityCallback, &context))
		{
			if(SCNetworkReachabilityScheduleWithRunLoop(reachabilityRef, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode))
			{
				retVal = YES;
			}
		}
	}
	
	return retVal;
}

- (void) stopNotifier
{
	if(reachabilityRef!= NULL)
	{
		SCNetworkReachabilityUnscheduleFromRunLoop(reachabilityRef, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
	}
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
	switch (buttonIndex) {
			case 0://不在显示
      bShowAlert = NO;
				break;
			case 1://确定
      bShowAlert = YES;
				break;
	}
  
  printf("\n net test:%d\n",buttonIndex);
}

/**
 * 获得uuid
 *
 * 修改记录：改成获得mac地址   by 郭伟坤
 */
-(void)getUUID
{
	/*
	[SettingsProperty sharedProperty].uuid = [[UIDevice currentDevice] uniqueIdentifier];
	if ([[SettingsProperty sharedProperty].uuid length] == 0) {
		[SettingsProperty sharedProperty].uuid = [NSString stringWithFormat:@""];
	}
	 */
	
	// 获得mac地址
	/*char* macAddressString= (char*)malloc(18);
	NSString* macAddress= [[NSString alloc] initWithCString:getMacAddress(macAddressString,"en0")
												   encoding:NSMacOSRomanStringEncoding];
	/*[SettingsProperty sharedProperty].uuid = macAddress;
	if ([[SettingsProperty sharedProperty].uuid length] == 0) {
		[SettingsProperty sharedProperty].uuid = [NSString stringWithFormat:@""];
	}*/
	//NSLog([SettingsProperty sharedProperty].uuid);
	
	// 获得设备的序列号
//	[SettingsProperty sharedProperty].serialNumber = [[UIDevice currentDevice] serialnumber];
//	NSLog(@"[SettingsProperty sharedProperty].serialNumber = %@",[SettingsProperty sharedProperty].serialNumber);
	//[SettingsProperty sharedProperty].serialNumber = @"";
	
	// 把“:”去掉
	//NSString *snString = [macAddress stringByReplacingOccurrencesOfString:@":" withString:@""];
}


@end
